package com.spsy.pay.controller;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.math.BigDecimal;
import java.math.RoundingMode; // 新增：导入舍入模式类
import java.util.Date;
import java.text.SimpleDateFormat;

public class PaymentOrderDataInsert {
    // 数据库配置
    private static final String URL = "jdbc:mysql://localhost:3306/ry_2303a_cloud?useSSL=false&rewriteBatchedStatements=true";
    private static final String USER = "root";
    private static final String PASSWORD = "root";

    // 任务参数
    private static final int TOTAL_RECORDS = 5000000; // 总记录数
    private static final int THREAD_COUNT = 8; // 线程数
    private static final int BATCH_SIZE = 1000; // 每批插入数量

    public static void main(String[] args) throws Exception {
        long startTime = System.currentTimeMillis();

        // 创建固定线程池
        ExecutorService executor = Executors.newFixedThreadPool(THREAD_COUNT);
        List<Future<?>> futures = new ArrayList<>();

        // 分配任务
        int recordsPerThread = TOTAL_RECORDS / THREAD_COUNT;
        int remaining = TOTAL_RECORDS % THREAD_COUNT;
        int startIndex = 0;

        for (int i = 0; i < THREAD_COUNT; i++) {
            int endIndex = startIndex + recordsPerThread + (i < remaining ? 1 : 0);
            futures.add(executor.submit(new InsertTask(startIndex, endIndex)));
            startIndex = endIndex;
        }

        // 等待所有任务完成
        for (Future<?> future : futures) {
            future.get();
        }

        // 关闭资源
        executor.shutdown();
        long endTime = System.currentTimeMillis();
        System.out.println("插入完成！共插入 " + TOTAL_RECORDS + " 条数据，耗时 " + (endTime - startTime) + " 毫秒");
    }

    static class InsertTask implements Runnable  {
        private final int start;
        private final int end;

        InsertTask(int start, int end) {
            this.start = start;
            this.end = end;
        }

        @Override
        public void run() {
            Connection conn = null;
            PreparedStatement pstmt = null;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                // 获取数据库连接
                conn = DriverManager.getConnection(URL, USER, PASSWORD);
                conn.setAutoCommit(false); // 手动控制事务

                // 准备插入SQL
                String sql = "INSERT INTO paymentorder " +
                        "(order_no, merchant_id, merchant_name, merchant_order_no, total_amount, discount_amount, pay_amount, " +
                        "pay_channel, pay_method, order_status, product_name, product_desc, user_id, user_ip, create_time, " +
                        "update_time, expire_time, pay_time, third_order_no, third_response, notify_url, notify_status, " +
                        "notify_count, error_code, error_msg) " +
                        "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                pstmt = conn.prepareStatement(sql);

                int count = 0;
                for (int i = start; i < end; i++) {
                    long currentTime = System.currentTimeMillis();
                    Date now = new Date(currentTime);
                    Date expireTime = new Date(currentTime + 3600 * 1000); // 过期时间为1小时后

                    // 设置参数（重点修改BigDecimal相关部分，添加舍入模式）
                    pstmt.setString(1, "PAY" + currentTime + i); // order_no
                    pstmt.setString(2, "MER" + (1000 + (i % 100))); // merchant_id
                    pstmt.setString(3, "XX科技有限公司" + (i % 5)); // merchant_name
                    pstmt.setString(4, "MORD" + currentTime + i); // merchant_order_no
                    // 重点修改：添加RoundingMode.HALF_UP（四舍五入）
                    pstmt.setBigDecimal(5, new BigDecimal(Math.random() * 5000 + 100).setScale(2, RoundingMode.HALF_UP)); // total_amount
                    pstmt.setBigDecimal(6, new BigDecimal(Math.random() * 100).setScale(2, RoundingMode.HALF_UP)); // discount_amount
                    pstmt.setBigDecimal(7, new BigDecimal(Math.random() * 4900 + 100).setScale(2, RoundingMode.HALF_UP)); // pay_amount
                    pstmt.setString(8, getRandomElement(new String[]{"ALIPAY", "WECHAT", "UNIONPAY"})); // pay_channel
                    pstmt.setString(9, getRandomElement(new String[]{"QRCODE", "APP", "H5"})); // pay_method
                    pstmt.setByte(10, (byte)(Math.random() > 0.7 ? 2 : 1)); // order_status（1-待支付，2-已支付）
                    pstmt.setString(11, "商品" + (i % 20)); // product_name
                    pstmt.setString(12, "商品详细描述" + i); // product_desc
                    pstmt.setString(13, "USER" + (10000 + (i % 1000))); // user_id
                    pstmt.setString(14, "192.168." + (i % 255) + "." + (i % 255)); // user_ip
                    pstmt.setString(15, sdf.format(now)); // create_time
                    pstmt.setString(16, sdf.format(now)); // update_time
                    pstmt.setString(17, sdf.format(expireTime)); // expire_time
                    pstmt.setString(18, Math.random() > 0.7 ? sdf.format(new Date(currentTime - (long)(Math.random() * 3600 * 1000))) : null); // pay_time
                    pstmt.setString(19, Math.random() > 0.7 ? "THIRD" + currentTime + i : null); // third_order_no
                    pstmt.setString(20, Math.random() > 0.7 ? "{\"code\":\"SUCCESS\",\"msg\":\"成功\"}" : null); // third_response
                    pstmt.setString(21, "http://notify.example.com/" + i); // notify_url
                    pstmt.setByte(22, (byte)(Math.random() > 0.5 ? 1 : 0)); // notify_status（0-未通知，1-已通知）
                    pstmt.setByte(23, (byte)(Math.random() * 5)); // notify_count
                    pstmt.setString(24, Math.random() > 0.9 ? "ERR_" + (i % 100) : null); // error_code
                    pstmt.setString(25, Math.random() > 0.9 ? "错误信息" + i : null); // error_msg
                    pstmt.addBatch();
                    count++;

                    // 达到批量大小执行一次
                    if (count % BATCH_SIZE == 0) {
                        pstmt.executeBatch();
                        conn.commit();
                        pstmt.clearBatch();
                    }
                }

                // 处理剩余数据
                if (count % BATCH_SIZE != 0) {
                    pstmt.executeBatch();
                    conn.commit();
                }

                System.out.println(Thread.currentThread().getName() + " 完成插入 " + (end - start) + " 条数据");

            } catch (SQLException e) {
                if (conn != null) {
                    try {
                        conn.rollback();
                    } catch (SQLException ex) {
                        ex.printStackTrace();
                    }
                }
                e.printStackTrace();
            } finally {
                // 关闭资源
                try { if (pstmt != null) pstmt.close(); } catch (SQLException e) {}
                try { if (conn != null) conn.close(); } catch (SQLException e) {}
            }
        }

        // 获取随机元素
        private String getRandomElement(String[] arr) {
            return arr[(int)(Math.random() * arr.length)];
        }
    }
}